package com.wu.advapplication;

import android.Manifest;
import android.app.Activity;
import android.app.ActivityManager;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.PixelFormat;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.Settings;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Toast;

import com.demo.baseutils.base.BaseUtils;
import com.wu.advapplication.servise.CustomTestService;
import com.wu.advapplication.servise.ForegroundService;
import com.wu.advapplication.utils.BaseUtil;
import com.wu.advapplication.utils.JumpPermissionManagement;
import com.wu.advapplication.utils.KeepManager;
import com.wu.advapplication.utils.SettingsCompat;

import java.util.Timer;
import java.util.TimerTask;

public class MainActivity extends Activity {
    private Context context;
    private static final String TAG = MainActivity.class.getSimpleName();

    private static int PERMISSION_SETTING_FOR_RESULT = 666;
    private static int PERMISSION_SETTING = 777;
    private final int REQUEST_OVERLAY_PERMISSION = 888;
    private WindowManager wm;
    private ImageView mImageView;
    private int position = 0;
    private final Timer timerMail = new Timer();
    public static String LOG_SAVE_PATH = Environment.getExternalStorageDirectory().getAbsolutePath() + "/download/advlogs/";
    private String[] permissions = {
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.WRITE_EXTERNAL_STORAGE};
    private boolean isWindowPermission = false;
    private SharedPreferences preferences;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
            BaseUtil.translucentActivity(this);
        }
        super.onCreate(savedInstanceState);
        context = this;
        preferences = this.getSharedPreferences("ADV_APP", 0);
//        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
//            ActivityCompat.requestPermissions(this, permissions, PERMISSION_SETTING);
//        }

        //开启1像素act
//        KeepManager.getInstance().registerKeep(context);

        //JobSchedule拉活
//        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
//            MyJobService.startJob(this);
//        }

        //双进程保活
//        startService(new Intent(this, LocalService.class));
//        startService(new Intent(this, RemoteService.class));

//        TextView textView = new TextView(this);
//        textView.setPadding(15, 15, 15, 0);
//        textView.setText("玉念聿辉：如果点不动界面，请不用担心，长按我试试！");
//        textView.setOnLongClickListener(new View.OnLongClickListener() {
//            @Override
//            public boolean onLongClick(View view) {
//                System.exit(0);
//                return false;
//            }
//        });
//        setContentView(R.layout.activity_main);

//        mImageView = new ImageView(this);
//        mImageView.setBackgroundResource(R.drawable.img_1);
//        mImageView.setOnLongClickListener(new View.OnLongClickListener() {
//
//            @Override
//            public boolean onLongClick(View v) {
//                // TODO Auto-generated method stub
//                wm.removeView(mImageView);
//                return false;
//            }
//        });
//
//        mImageView.setOnClickListener(new View.OnClickListener() {
//
//            @Override
//            public void onClick(View v) {
//                // TODO Auto-generated method stub
//                position++;
//                if (position == 1) {
//                    mImageView.setBackgroundResource(R.drawable.img_1);
//                } else if (position == 2) {
//                    mImageView.setBackgroundResource(R.drawable.img_2);
//                } else if (position == 3) {
//                    mImageView.setBackgroundResource(R.drawable.img_3);
//                    position = 0;
//                }
//                Toast.makeText(getApplication(), "你再点一个试试", Toast.LENGTH_SHORT)
//                        .show();
//            }
//        });


//        timerMail.schedule(new TimerTask() {
//            @Override
//            public void run() {
//                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
//                    if (Settings.canDrawOverlays(context)) {
//                        preferences.edit().putBoolean("isWindowPermission", true).commit();
//                        if (!BaseUtil.isServiceRunning(context, CustomTestService.class.getName())) {
//                            Log.e(TAG, "run: 服务没启动-------");
//                            startService(new Intent(context, CustomTestService.class));
//                        }
//                    } else {
//                        preferences.edit().putBoolean("isWindowPermission", false).commit();
//                    }
//                }
//                MainActivity.this.runOnUiThread(new Runnable() {
//                    @Override
//                    public void run() {
////                        Toast.makeText(context, "请授权！" + getTaskId(), Toast.LENGTH_SHORT).show();
//                        //实时监听页面是否在栈顶
//                        if (!BaseUtil.getTopApp(context, MainActivity.class)) {
////                            Log.e(TAG, "run: act还在转为前台");
//                            ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
//                            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
//                                am.moveTaskToFront(getTaskId(), ActivityManager.MOVE_TASK_WITH_HOME);
//                            }
//                        }
//                    }
//                });
//
//            }
//        }, 0, 100);


    }

    @Override
    protected void onResume() {
        super.onResume();
//        requestPermission();
//        if (!BaseUtil.isServiceRunning(context, ForegroundService.class.getName())) {
//            startService(new Intent(this, ForegroundService.class));
//        }
        BaseUtils.INSTANCE.setAutoStartPackager(this);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
//        KeepManager.getInstance().unRegisterKeep(context);
    }

    /**
     * 权限
     */
    public void requestPermission() {
        Log.i(TAG, "requestPermission是否打开过悬浮窗权限：" + preferences.getBoolean("isWindowPermission", true));
        //弹框
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            if (!SettingsCompat.canDrawOverlays(context) && !preferences.getBoolean("isWindowPermission", true)) {
                Log.e(TAG, "requestPermission: 申请打开悬浮窗权限--------1");
                SettingsCompat.manageDrawOverlays(context);
            } else {
                if (!BaseUtil.isServiceRunning(context, CustomTestService.class.getName())) {
                    startService(new Intent(this, CustomTestService.class));
                    Log.e(TAG, "requestPermission:已开启悬浮窗权限---3");
                }
                return;
            }
        } else {
            //19以下直接返回
            return;
        }
        Log.e(TAG, "requestPermission: 打开权限页面---2");
//        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
//            if (!preferences.getBoolean("isWindowPermission", true) && !Settings.canDrawOverlays(this)) {
//                Intent intent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION, Uri.parse("package:" + getPackageName()));
//                startActivityForResult(intent, REQUEST_OVERLAY_PERMISSION);
//            } else {
//                if (!BaseUtil.isServiceRunning(context, CustomTestService.class.getName())) {
//                    startService(new Intent(this, CustomTestService.class));
//                    Log.e(TAG, "requestPermission:已开启悬浮窗权限 ");
//                }
//                return;
//            }
//        }

        //打开权限页面，主要设置允许后台打开程序以及自启等
        JumpPermissionManagement.GoToSetting(this);

        //打开应用详情页面
        JumpPermissionManagement.openAppDetailSetting(this);

        //申请白名单权限
        JumpPermissionManagement.PowerService(this);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        Log.e(TAG, "onActivityResult-----------" + requestCode);
        //先检查普通权限
        if (requestCode == PERMISSION_SETTING) {
            Log.e(TAG, "onActivityResult----------- 普通权限");
        } else if (requestCode == PERMISSION_SETTING_FOR_RESULT) {
            Log.e(TAG, "onActivityResult----------- 设置页面和白名单");
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && !Settings.canDrawOverlays(this)) {
                Toast.makeText(context, "请打开所有权限", Toast.LENGTH_SHORT).show();
                requestPermission();
            }
        } else if (requestCode == REQUEST_OVERLAY_PERMISSION) {
            Log.e(TAG, "onActivityResult----------- 悬浮窗");
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && Settings.canDrawOverlays(this)) {
                if (!BaseUtil.isServiceRunning(context, CustomTestService.class.getName())) {
                    preferences.edit().putBoolean("isWindowPermission", true).commit();
                    startService(new Intent(this, CustomTestService.class));
                }
            } else {
                Toast.makeText(context, "请打开所有权限", Toast.LENGTH_SHORT).show();
                requestPermission();
            }
        }
    }

    public void showSuspensionWindow(View mView) {
        Log.i(TAG, "showSuspensionWindow: 显示");
        wm = (WindowManager) getSystemService(WINDOW_SERVICE);
        WindowManager.LayoutParams param = new WindowManager.LayoutParams();
        param = new WindowManager.LayoutParams();
        if (Build.VERSION.SDK_INT >= 26) {
            param.type = WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY;
        } else {
            param.type = WindowManager.LayoutParams.TYPE_SYSTEM_ALERT;
        }
        param.flags = WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL
                | WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
                | WindowManager.LayoutParams.FLAG_FULLSCREEN
                | WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN;
        param.format = PixelFormat.RGBA_8888;
        param.gravity = Gravity.CENTER;
        param.x = WindowManager.LayoutParams.MATCH_PARENT;
        param.y = WindowManager.LayoutParams.MATCH_PARENT;

        // 设置悬浮窗口长宽数据
        param.width = WindowManager.LayoutParams.MATCH_PARENT;
        param.height = WindowManager.LayoutParams.MATCH_PARENT;

        //弄个LinearLayout
        LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
                WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.MATCH_PARENT);
        lp.gravity = Gravity.CENTER;
        LinearLayout view = new LinearLayout(getApplication());
        view.setLayoutParams(lp);// 设置布局参数
        // view.setBackgroundColor(Color.parseColor("#000000"));
        view.setGravity(Gravity.CENTER);
        view.addView(mView);

        wm.addView(view, param);
    }


    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        // TODO Auto-generated method stub
        //屏蔽返回按钮
        if (KeyEvent.KEYCODE_BACK == event.getKeyCode()) {
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }
}
